from playwright.sync_api import Page

from model.ProConfModel import ProConfModel
from tools.HtmlPageService import get_selector_src
from tools.Ocr import get_by_base64



def is_login_success(page: Page, target_url: str,timeout: int = 1000):
    try:
        page.wait_for_url(target_url, timeout=timeout)
        print(f"页面成功跳转到目标URL: {target_url}")
        return True
    except Exception as e:
        print(f"未跳转到目标URL: {str(e)}")
        return False


def login_with_validate_code(
    page: Page,
    pro_conf: ProConfModel
) -> bool:
    is_login=False

    for i in range(3):
        do_login(page, pro_conf)

        is_login= is_login_success(page, "https://passport.crecgec.com/userCenter?type=Cente")

        if is_login:
            return True

    # 等待登录接口响应
    page.wait_for_timeout(100)  # 简单延迟，确保响应已捕获

    return is_login


def do_login( page: Page,   pro_conf: ProConfModel):

    """执行带滑块验证的登录，并返回登录接口的 JSON 数据"""
    page.goto(pro_conf.login_url, wait_until="networkidle", timeout=15000)
    page.get_by_role("textbox", name="请输入用户名或邮箱").fill(pro_conf.login_name )
    page.get_by_role("textbox", name="请输入密码").fill(pro_conf.login_password)
    page.wait_for_selector(".verificationCode.code-cursor", state="visible")
    base64_str = get_selector_src(page, ".verificationCode.code-cursor")
    validate_code = get_by_base64(base64_str)

    page.get_by_role("textbox", name="请输入图片验证码").fill(validate_code)

    page.get_by_role("button", name="登录").click()



